<?php
// Include database connection
require_once __DIR__ . '/../config/database.php';

// Create database connection
try {
    $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
    $conn = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// Include header
require_once 'includes/header.php';

// Get item ID
$item_id = isset($_GET['item']) ? (int)$_GET['item'] : 0;

// Handle file uploads
$max_file_size = 5 * 1024 * 1024; // 5MB
$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$upload_dir = '../images/';

// Handle actions
$message = '';
$message_type = '';

if (isset($_POST['action'])) {
    $action = $_POST['action'];
    
    switch ($action) {
        case 'upload_image':
            if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
                $message = '上传文件失败，请重试';
                $message_type = 'danger';
                break;
            }
            
            $file = $_FILES['image'];
            $title = isset($_POST['title']) ? trim($_POST['title']) : '';
            $description = isset($_POST['description']) ? trim($_POST['description']) : '';
            $is_thumbnail = isset($_POST['is_thumbnail']) ? 1 : 0;
            
            // Validate file
            if ($file['size'] > $max_file_size) {
                $message = '文件太大，最大允许5MB';
                $message_type = 'danger';
                break;
            }
            
            if (!in_array($file['type'], $allowed_types)) {
                $message = '不支持的文件类型，只允许JPEG、PNG、GIF和WEBP格式';
                $message_type = 'danger';
                break;
            }
            
            try {
                // Get item and module info
                $sql = "SELECT i.id, i.name, m.slug as module_slug 
                        FROM km_cognitive_items i
                        JOIN km_cognitive_modules m ON i.module_id = m.id
                        WHERE i.id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->execute([$item_id]);
                $stmt->execute();
                // PDO直接使用$stmt，无需get_result
                
                if ($result->num_rows === 0) {
                    $message = '找不到指定的模块内容';
                    $message_type = 'danger';
                    break;
                }
                
                $item_info = $result->fetch(PDO::FETCH_ASSOC);
                $module_slug = $item_info['module_slug'];
                
                // Create directory if it doesn't exist
                $item_dir = $upload_dir . $module_slug . '/';
                if (!file_exists($item_dir)) {
                    mkdir($item_dir, 0755, true);
                }
                
                // Generate unique filename
                $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                $base_name = strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $item_info['name']));
                
                // Get the max display order
                $sql = "SELECT MAX(display_order) as max_order FROM km_cognitive_item_images WHERE item_id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->execute([$item_id]);
                $stmt->execute();
                // PDO直接使用$stmt，无需get_result
                $row = $result->fetch(PDO::FETCH_ASSOC);
                $display_order = ($row['max_order'] ?? 0) + 1;
                
                // Generate filename
                $filename = $base_name . '-' . $display_order . '.' . $file_extension;
                $file_path = $item_dir . $filename;
                
                // Move uploaded file
                if (move_uploaded_file($file['tmp_name'], $file_path)) {
                    // Save to database
                    $image_path = 'images/' . $module_slug . '/' . $filename;
                    
                    $sql = "INSERT INTO km_cognitive_item_images 
                            (item_id, image_path, title, description, is_thumbnail, display_order) 
                            VALUES (?, ?, ?, ?, ?, ?)";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$item_id, $image_path, $title, $description, $is_thumbnail, $display_order]);
                    $stmt->execute();
                    
                    if ($stmt->rowCount() > 0) {
                        $message = '图片已成功上传';
                        $message_type = 'success';
                        
                        // If this is a thumbnail, update other images
                        if ($is_thumbnail) {
                            $sql = "UPDATE km_cognitive_item_images SET is_thumbnail = 0 
                                    WHERE item_id = ? AND id != ?";
                            $stmt = $conn->prepare($sql);
                            $stmt->execute([$item_id, $conn->insert_id]);
                            $stmt->execute();
                        }
                    } else {
                        $message = '图片上传成功，但无法保存到数据库';
                        $message_type = 'warning';
                    }
                } else {
                    $message = '无法移动上传的文件';
                    $message_type = 'danger';
                }
            } catch (Exception $e) {
                $message = '数据库错误: ' . $e->getMessage();
                $message_type = 'danger';
            }
            break;
            
        case 'update_image':
            $image_id = isset($_POST['image_id']) ? (int)$_POST['image_id'] : 0;
            $title = isset($_POST['title']) ? trim($_POST['title']) : '';
            $description = isset($_POST['description']) ? trim($_POST['description']) : '';
            $is_thumbnail = isset($_POST['is_thumbnail']) ? 1 : 0;
            $display_order = isset($_POST['display_order']) ? (int)$_POST['display_order'] : 0;
            
            try {
                $sql = "UPDATE km_cognitive_item_images SET 
                        title = ?, description = ?, display_order = ?
                        WHERE id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->execute([$title, $description, $display_order, $image_id]);
                $stmt->execute();
                
                // If thumbnail status changed
                if ($is_thumbnail) {
                    $sql = "UPDATE km_cognitive_item_images SET is_thumbnail = 0 
                            WHERE item_id = ? AND id != ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$item_id, $image_id]);
                    $stmt->execute();
                    
                    $sql = "UPDATE km_cognitive_item_images SET is_thumbnail = 1 
                            WHERE id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$image_id]);
                    $stmt->execute();
                }
                
                $message = '图片信息已成功更新';
                $message_type = 'success';
            } catch (Exception $e) {
                $message = '数据库错误: ' . $e->getMessage();
                $message_type = 'danger';
            }
            break;
            
        case 'delete_image':
            $image_id = isset($_POST['image_id']) ? (int)$_POST['image_id'] : 0;
            
            try {
                // Get image path
                $sql = "SELECT image_path FROM km_cognitive_item_images WHERE id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->execute([$image_id]);
                $stmt->execute();
                // PDO直接使用$stmt，无需get_result
                
                if ($result->num_rows > 0) {
                    $image_path = $result->fetch(PDO::FETCH_ASSOC)['image_path'];
                    $full_path = '../' . $image_path;
                    
                    // Delete from database
                    $sql = "DELETE FROM km_cognitive_item_images WHERE id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$image_id]);
                    $stmt->execute();
                    
                    if ($stmt->rowCount() > 0) {
                        // Delete file if it exists
                        if (file_exists($full_path)) {
                            unlink($full_path);
                        }
                        
                        $message = '图片已成功删除';
                        $message_type = 'success';
                    } else {
                        $message = '无法删除图片';
                        $message_type = 'danger';
                    }
                } else {
                    $message = '找不到指定的图片';
                    $message_type = 'danger';
                }
            } catch (Exception $e) {
                $message = '数据库错误: ' . $e->getMessage();
                $message_type = 'danger';
            }
            break;
    }
}

// Get item info and images
$item_info = null;
$images = [];

if ($item_id > 0) {
    try {
        // Get item info
        $sql = "SELECT i.id, i.name, i.module_id, m.name as module_name, m.slug as module_slug 
                FROM km_cognitive_items i
                JOIN km_cognitive_modules m ON i.module_id = m.id
                WHERE i.id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->execute([$item_id]);
        $stmt->execute();
        // PDO直接使用$stmt，无需get_result
        
        if ($result->num_rows > 0) {
            $item_info = $result->fetch(PDO::FETCH_ASSOC);
            
            // Get images for this item
            $sql = "SELECT id, image_path, title, description, is_thumbnail, display_order 
                    FROM km_cognitive_item_images
                    WHERE item_id = ?
                    ORDER BY display_order ASC";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$item_id]);
            $stmt->execute();
            // PDO直接使用$stmt，无需get_result
            
            while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
                $images[] = $row;
            }
        }
    } catch (Exception $e) {
        $message = '数据库错误: ' . $e->getMessage();
        $message_type = 'danger';
    }
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">图片管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <?php if ($item_id > 0): ?>
            <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#uploadImageModal">
                <i class="bi bi-upload"></i> 上传图片
            </button>
            <?php endif; ?>
            <a href="items.php<?php echo $item_id ? '?module=' . $item_info['module_id'] : ''; ?>" class="btn btn-sm btn-outline-secondary">返回模块内容</a>
        </div>
    </div>
</div>

<?php if (!empty($message)): ?>
<div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
    <?php echo $message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>

<?php if ($item_id > 0 && $item_info): ?>
<div class="alert alert-info">
    正在管理 <strong><?php echo htmlspecialchars($item_info['module_name']); ?></strong> 模块中的
    <strong><?php echo htmlspecialchars($item_info['name']); ?></strong> 的图片
</div>

<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-primary">图片列表</h6>
        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#uploadImageModal">
            <i class="bi bi-upload"></i> 上传图片
        </button>
    </div>
    <div class="card-body">
        <?php if (empty($images)): ?>
        <div class="alert alert-warning">
            此模块内容还没有添加任何图片。点击"上传图片"按钮添加图片。
        </div>
        <?php else: ?>
        <div class="row">
            <?php foreach ($images as $image): ?>
            <div class="col-md-4 col-sm-6 mb-4">
                <div class="card h-100">
                    <div class="position-relative">
                        <img src="../<?php echo $image['image_path']; ?>" class="card-img-top" alt="<?php echo htmlspecialchars($image['title'] ?: $item_info['name']); ?>">
                        <?php if ($image['is_thumbnail']): ?>
                        <span class="position-absolute top-0 start-0 badge bg-success m-2">缩略图</span>
                        <?php endif; ?>
                    </div>
                    <div class="card-body">
                        <h5 class="card-title"><?php echo htmlspecialchars($image['title'] ?: '无标题'); ?></h5>
                        <p class="card-text"><?php echo htmlspecialchars($image['description'] ?: '无描述'); ?></p>
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="badge bg-secondary">顺序: <?php echo $image['display_order']; ?></span>
                            <div>
                                <button type="button" class="btn btn-sm btn-primary btn-edit-image" 
                                    data-id="<?php echo $image['id']; ?>"
                                    data-title="<?php echo htmlspecialchars($image['title']); ?>"
                                    data-description="<?php echo htmlspecialchars($image['description']); ?>"
                                    data-thumbnail="<?php echo $image['is_thumbnail']; ?>"
                                    data-order="<?php echo $image['display_order']; ?>"
                                    data-bs-toggle="modal" data-bs-target="#editImageModal">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button type="button" class="btn btn-sm btn-danger btn-delete-image" 
                                    data-id="<?php echo $image['id']; ?>"
                                    data-bs-toggle="modal" data-bs-target="#deleteImageModal">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Upload Image Modal -->
<div class="modal fade" id="uploadImageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload_image">
                
                <div class="modal-header">
                    <h5 class="modal-title">上传图片</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="image" class="form-label">选择图片</label>
                        <input type="file" class="form-control" id="image" name="image" accept="image/*" required>
                        <div class="form-text">允许的格式：JPEG, PNG, GIF, WEBP，最大大小：5MB</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="title" class="form-label">标题</label>
                        <input type="text" class="form-control" id="title" name="title">
                    </div>
                    
                    <div class="mb-3">
                        <label for="description" class="form-label">描述</label>
                        <textarea class="form-control" id="description" name="description" rows="2"></textarea>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="is_thumbnail" name="is_thumbnail">
                        <label class="form-check-label" for="is_thumbnail">
                            设为缩略图
                        </label>
                        <div class="form-text">缩略图会在模块内容列表中显示</div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">上传</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Image Modal -->
<div class="modal fade" id="editImageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" name="action" value="update_image">
                <input type="hidden" name="image_id" id="edit_image_id">
                
                <div class="modal-header">
                    <h5 class="modal-title">编辑图片信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="edit_title" class="form-label">标题</label>
                        <input type="text" class="form-control" id="edit_title" name="title">
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_description" class="form-label">描述</label>
                        <textarea class="form-control" id="edit_description" name="description" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_display_order" class="form-label">显示顺序</label>
                        <input type="number" class="form-control" id="edit_display_order" name="display_order" min="1" required>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="edit_is_thumbnail" name="is_thumbnail">
                        <label class="form-check-label" for="edit_is_thumbnail">
                            设为缩略图
                        </label>
                        <div class="form-text">缩略图会在模块内容列表中显示</div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Image Modal -->
<div class="modal fade" id="deleteImageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" name="action" value="delete_image">
                <input type="hidden" name="image_id" id="delete_image_id">
                
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                
                <div class="modal-body">
                    <p>确定要删除这张图片吗？此操作不可撤销。</p>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-danger">删除</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Edit image modal
    $('.btn-edit-image').on('click', function() {
        var id = $(this).data('id');
        var title = $(this).data('title');
        var description = $(this).data('description');
        var thumbnail = $(this).data('thumbnail');
        var order = $(this).data('order');
        
        $('#edit_image_id').val(id);
        $('#edit_title').val(title);
        $('#edit_description').val(description);
        $('#edit_is_thumbnail').prop('checked', thumbnail == 1);
        $('#edit_display_order').val(order);
    });
    
    // Delete image modal
    $('.btn-delete-image').on('click', function() {
        var id = $(this).data('id');
        $('#delete_image_id').val(id);
    });
    
    // Preview image before upload
    $('#image').on('change', function() {
        var file = this.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#image_preview').attr('src', e.target.result).show();
            }
            reader.readAsDataURL(file);
        }
    });
});
</script>

<?php else: ?>
<div class="alert alert-warning">
    请从模块内容管理页面选择一个模块内容项来管理其图片。
</div>
<?php endif; ?>

<?php
// Include footer
require_once 'includes/footer.php';
?> 